<template>
  <view>
    <PublicPage ref="publicRef" :showHead="false" class="qqp-index-container">
      <!-- 自定义导航栏 -->
      <u-navbar height="48" :is-back="false">
        <view class="slot-wrap items-center">
          <image src="https://image.qqpyyds.com/mpAppImg/other/new_logo.png" class="logo" />
          <view v-if="scroll.top>=118" class="search-icon" @click.stop="_onSearch">
            <i class="iconfont icon-search" />
          </view>
        </view>
      </u-navbar>
      <ScrollList
          ref="scrollView"
          :minusHeight="navBottom"
          :scrollAnimation="false"
          isFixed
          @interrupt="interrupt"
          @scrolltolower="scrolltolower"
          @scroll="_onScroll"
      >
        <template slot="content">
          <view class="header-wrap">
            <view class="group_5">
              <text class="text">{{playvolumeFn(topDetail.communityCount) || 0}}个社群 | {{playvolumeFn(topDetail.dynamicCount) || 0}}个创作 | {{playvolumeFn(topDetail.joinCount) || 0}}人参与</text>
            </view>
            <veiw class="swiper_view">
              <swiper
                  class="swiper_box"
                  :indicator-dots="false"
                  :interval="3000"
                  :duration="100"
                  :autoplay="true"
                  :current="current"
                  :disable-touch="false"
                  :touchable="false"  
                  circular
                  vertical
              >
                <swiper-item v-for="(item, index) in topDetail.scrollMessageList" :key="index" @touchmove.stop>
                  <view class="swiper_item">{{item}}</view>
                </swiper-item>
              </swiper>
            </veiw>
            <!-- 搜索框 -->
            <view class="search-content">
              <SearchInput
                  :hasBorder="false"
                  :focusType="focusType"
                  placeholder="输入搜索内容"
                  @searchFn="searchFn"
                  @blur="_onBlur"
              />
            </view>
            <!-- 标签切换 -->
            <view class="tabs-wrap" :class="{ radius: !getParams.type }">
              <u-tabs
                  active-color="#E44435"
                  height="88"
                  inactive-color="#969799"
                  font-size="28"
                  name="label"
                  bar-width="80"
                  :bold="false"
                  item-width="154"
                  :list="filterTabs"
                  :is-scroll="false"
                  :current="getParams.type"
                  @change="_changeCurrent"
              />
            </view>
          </view>
          <!-- 可帮卖筛选按钮 -->
          <view v-if="getParams.type" id="groupButton2" class="groupButton justify-between groupSticky">
            <view
                v-for="el in filterButtons"
                :key="el.value"
                class="buttonItem"
                :class="{active:getParams.sortType===el.value}"
                @click.stop="_handleBtn(el)"
            >{{el.label}}</view>
          </view>
          <template v-if="dynamicList.length || listLoading">
            <DynamicCard :type="1" :list="dynamicList" :loading="listLoading" @groupBtn="_dynamicGroupBtn" />
          </template>
          <!-- 缺省状态 -->
          <view v-else-if="!dynamicList.length&&isEmpty" :style="{height: 'calc(100vh - '+emptyHeight+'px)'}">
            <DefaultPage :minusHeight="getParams.type?0:47" :type="defaultType" :tips="defaultTip" />
          </view>
        </template>
      </ScrollList>
      <!-- 关注公众号 -->
      <view v-if="!isLogin" class="attention-official-account" :style="{bottom:attentionBottom+'px;height:170rpx;'}">
        <official-account></official-account>
      </view>
      <!-- dlAttention&&(!userInfo.isSubscribe||userInfo.isSubscribe==0) -->
      <view v-if="isLogin&&userInfo.isSubscribe==0" class="attention-official-account" :style="{bottom:attentionBottom+'px'}">
        <view class="attentionContent">
          <view class="left">
            <!-- <i class="iconfont icon-close" @click.stop="_closeAttention"/> -->
            <text>点击关注服务号，立享四大特权！</text>
          </view>
          <view>
            <button type="error" class="go_attention" @click.stop="_goAttention">去关注</button>
          </view>
        </view>
      </view>
    </PublicPage>
    <!-- 开团成功海报 -->
    <OpenGroupSharing ref="shareChild" @shareSuccess="_shareSuccess" />
    <PublishPopup v-if="dlGroup" :sharePublishData="shareObject" @closeSharePublishFn="(flag)=>dlGroup=flag" />
    <!-- 动态分享、邀请帮卖 -->
    <SharePublicPage
        v-if="dlShare"
        :shareVideoData="shareObject"
        @cancelShareFn="(flag) => dlShare = false"
        @posterFn="_posterFn"
    />
    <!-- 保存相册海报分享 -->
    <SharePoster
        v-if="dlPoster"
        :shareVideoData="shareObject"
        @cancelSharePosterFn="() => dlPoster = false"
    />
    <!-- 关注公众号弹框 -->
    <attendOfficial
        v-if="dlAttendOfficial"
        :show="dlAttendOfficial"
        :text="attendOfficialText"
        :isRefresh="true"
        @close="dlAttendOfficial=false"
    />
    <!-- 已经帮卖弹窗 -->
    <SoldForHelpSell v-if="isSoldForHelpSellShow" @closeSoldForFn="closeSoldForFn" :soldForHelpSellId="soldForHelpSellId" />
  </view>
</template>

<script>
import PublicPage from '@/components/publicPage/index.vue'
import ScrollList from '@/components/scrollList/index.vue'
import SearchInput from '@/components/searchInput/index.vue'
import DynamicCard from '@/components/dynamicCard/index.vue'
import DefaultPage from '@/components/defaultPage/index.vue'
import OpenGroupSharing from "@/components/shareImage/openGroupSharing.vue"
import PublishPopup from '@/components/publishPopup/index.vue'
import SharePublicPage from '@/components/shareModal/sharePublicPage.vue'
import SharePoster from '@/components/shareModal/sharePoster.vue'
import attendOfficial from '@/components/attendOfficial/index.vue'
import shareMixin from '@/components/dynamicCard/shareMixin'
import {filterButtons, filterTabs} from './tabs'
import miniApi from '@/api/mini.js'
import SoldForHelpSell from '@/components/soldForHelpSell/index.vue'
import Util from "@/api/util.js"

export default {
  name: 'Index',
  // 分享、海报相关在shareMixin中
  mixins: [shareMixin],
  components: {
    PublicPage,
    ScrollList,
    SearchInput,
    DefaultPage,
    DynamicCard,
    PublishPopup,
    OpenGroupSharing,
    SharePublicPage,
    SharePoster,
    attendOfficial,
    SoldForHelpSell
  },
  computed: {
    // 用户数据
    userInfo () {
      return this.$store.state.userInfo
    },
    // 底部tabbar的高度
    navBottom() {
      const systemObj = this.$store.state.globalData
      return systemObj.navBottom + 8
    },
    // 关注公众号的bottom定位
    attentionBottom() {
      const { model, navBottom } = this.$store.state.globalData
      if (model.indexOf('iPhone') !== -1) {
        return navBottom + 20
      } else {
        return navBottom
      }
    },
    // 空状态的高度
    emptyHeight() {
      const { navBottom, navHeight } = this.$store.state.globalData
      return navHeight + navBottom + 213
    }
  },
  data() {
    return {
      // dlAttention: true,// 关注公众号提示
      defaultType: 2, // 缺省页状态
      defaultTip: '暂时没有关注任何人哦～',
      topDetail: {
        communityCount: 0,
        dynamicCount: 0,
        joinCount: 0,
        scrollMessageList: [],
        shoppingCartCount: 0
      }, // 气泡+社区数量
      dynamicList: [], // 动态卡片列表
      filterTabs, // 筛选tab
      filterButtons, // 可帮卖按钮
      getParams: {
        currentPage: 1,
        pageSize: 10,
        type: 0,
        sortType: 1,
        keyword: ''
      }, // 筛选字段
      listMore: true, // 当前列表是否还有更多
      listLoading: true, // 加载骨架图
      scroll: { top: 0 },
      focusType: false, // 输入框获是否获取焦点
      isEmpty: true, // 是否显示空状态--配合dynamicList的长度使用，避免在页面一开始加载时先显示了空状态
      timeout: null,
      isSoldForHelpSellShow: false, // 帮卖过了不可帮卖
      soldForHelpSellId: '', // 已经帮卖返回自己帮卖团的id
    }
  },
  onLoad() {
    this.getDynamics()
  },
  onShow() {
    // 获取用户信息--检测用户是否已经关注公众号
    this.getInfoFn()
    if (this.getIsRefreshType() || !this.dynamicList.length) {
      this.listLoading = true
      this.listMore = true
      if (this.timeout) clearTimeout(this.timeout)
      // 需要页面需要刷新数据
      this.getParams.currentPage = 1
      this.getDynamics()
      this.setIsRefreshType(false)
    }
    this._getTopDetail()

    // 获取红点规则
    if(this.isLogin){
      miniApi.getMyPageInfo().then(res=>{
        this.$store.commit('SET_MY_PAGEINFO',res.data)
      })
    }
  },
  onHide() {
    // 清楚定时器标识
    if (this.timeout) clearTimeout(this.timeout)
  },
  methods: {
    closeSoldForFn () {
      this.isSoldForHelpSellShow = false
    },
    // 获取社群数量
    async _getTopDetail() {
      const res = await miniApi.topDetail()
      if (res.code === 200) {
        this.topDetail = res.data
      }
    },
    // 获取动态视频数据
    async getDynamics() {
      ++this.refreshNum
      // 入参
      const params = {
        currentPage: this.getParams.currentPage,
        pageSize: this.getParams.pageSize,
        type: this.getParams.type + 1
      }
      if (this.getParams.type === 1) {
        params.sortType = this.getParams.sortType
      }
      if (this.getParams.keyword) {
        params.keyword = this.getParams.keyword
      }
      miniApi.getHomeDynamics(params).then((res) => {
        this.getParams.total = res.data.total
        if (this.getParams.currentPage === 1) {
          this.dynamicList = res.data.records
          this.isEmpty = true
        } else {
          this.dynamicList = this.dynamicList.concat(res.data.records)
        }
        if ((this.getParams.currentPage * this.getParams.pageSize) !== this.dynamicList.length) {
          // 无更多数据标识
          this.listMore = false
          if(this.getParams.currentPage === 1){this.$refs.scrollView.loadFinish(3,0)} // 无更多数据
        }
      }).catch(err => {
        this.$refs.scrollView.loadFinish(3,0)
      })
      // 第一页才有骨架图
      if (this.getParams.currentPage === 1 && this.listLoading) {
        if (this.timeout) clearTimeout(this.timeout)
        // 隐藏骨架图标识
        this.timeout = setTimeout(() => {
          this.listLoading = false
          if (this.dynamicList.length > 0) {
            // 刷新数据--场景，从登录页面之后第一次进入
            this.$refs.scrollView.loadFinish(0)
          }
        }, 750)
      }
    },
    // 搜索
    searchFn(e) {
      this.getParams.keyword = e
      if (e) {
        this.defaultType = 3
        this.defaultTip = '暂未搜索相关结果，换个关键词试试～'
      } else {
        this.defaultType = 2
        this.defaultTip = '暂时没有关注任何人哦～'
      }
      this.getParams.currentPage = 1
      this.listMore = true
      this.getDynamics()
    },
    // 搜索失去焦点--重置搜索框的聚焦状态以及滚动位置
    _onBlur() {
      this.focusType = false
      this.$refs.scrollView.goToScroll(0)
    },
    // 自定义导航栏搜索按钮--点击定位到搜索框并拉起键盘
    _onSearch() {
      this.focusType = true
      this.$refs.scrollView.goToScroll(0)
    },
    // tabs标签切换
    _changeCurrent(val) {
      this.getParams.type = val
      this.getParams.currentPage = 1
      this.listMore = true
      this.$refs.scrollView.loadFinish(0)
      this.getDynamics()
    },
    // 筛选按钮
    _handleBtn(el) {
      if (el.value === this.getParams.sortType) return
      // 若是此时列表滚动位置已超过筛选按钮，则需要将滚动位置拉到筛选按钮吸顶初始化状态
      if (this.scroll.top > 167) this.$refs.scrollView.goToScroll(167)
      this.listMore = true
      this.getParams.currentPage = 1
      this.getParams.sortType = el.value
      this.$refs.scrollView.loadFinish(0)
      this.getDynamics()
    },
    // 滚动事件
    _onScroll(e) {
      this.scroll.top = e.detail.scrollTop
    },
    // 下拉刷新方法，刷新完毕调用组件方法改变状态
    interrupt() {
      if (this.timeout) clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        this.listMore = true
        this.getParams.currentPage = 1
        this.getDynamics()
        this.$refs.scrollView.refreshFinish() // 刷新完成
      }, 400);
    },
    // 底部加载更多
    scrolltolower(){
      ++this.getParams.currentPage
      this.getDynamics()
      this.$refs.scrollView.loadFinish(this.listMore ? 0 : 3) // 加载完成
    },
    // 跳转webview
    _goAttention() {
      this.setIsRefreshType(true)
      this.navigateTo({url: '/pagesA/components/WebView'})
    },
    // 处理数据过万的显示
    playvolumeFn (mun) {
      return Util.playvolume(mun)
    },
    // 关闭关注号提示
    // _closeAttention() {
    //   this.dlAttention = false
    // },
  }
}
</script>

<style lang="scss">
.qqp-index-container {
  width: 100%;
  .header-wrap {
    background-color: #ffffff;
  }
  // 去除自定义导航bottom线
  .u-border-bottom:after {
    border: none;
  }
  .slot-wrap {
    padding-left: 32rpx;
    .logo {
      width: 446rpx;
      height: 66rpx;
    }
    .search-icon {
      width: 48rpx;
      height: 48rpx;
      border-radius: 24rpx;
      text-align: center;
      line-height: 48rpx;
      color: #333333;
      background-color: $n2Color;
    }
  }
  .group_5 {
    padding: 10rpx 32rpx 8rpx;
    .text {
      color: $n8Color;
      font-size: 24rpx;
      line-height: 34rpx;
      white-space: nowrap;
    }
  }
  .swiper_view {
    .swiper_box {
      height: 44rpx;
      padding: 0 32rpx;
      box-sizing: border-box;
      .swiper_item {
        display: inline-block;
        font-size: 20rpx;
        padding: 4rpx 16rpx;
        color: #fff;
        background: #FFC3B5;
        border-radius: 100rpx;
        box-sizing: border-box;
      }
    }
  }
  .search-content {
    margin: 36rpx 0 8rpx;
    .searchBody {
      box-shadow: none;
    }
  }
  .tabs-wrap {
    background-color: #F7F8FA;
    //padding-bottom: 20rpx;
    .u-tabs {
      padding-left: 32rpx;
    }
    .u-scroll-box {
      justify-content: flex-start;
    }
    .u-tab-item {
      padding: 0 16rpx;
      flex: inherit !important;
    }
    // type == 0 tabs加底下radius
    &.radius .u-tabs {
      border-radius: 0 0 32rpx 32rpx;
    }
  }
  .groupButton {
    padding: 16rpx 32rpx;
    border-radius: 0 0 32rpx 32rpx;
    background-color: #ffffff;
    .buttonItem {
      padding: 12rpx 24rpx;
      color: $n8Color;
    }
    .active {
      border-radius: 44rpx;
      background-color: $n2Color;
    }
  }
  .groupSticky {
    position: sticky;
    left: 0;
    top: 0;
    z-index: 999;
  }
  .dynamicList {
    width: 100%;
    padding: 20rpx 24rpx 0;
  }
  .pullContent {
    position: absolute;
    top: -98rpx;
    left: 0;
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
  }
  .emptyContent {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding-top: 100rpx;
    .emptyImage {
      display: block;
      width: 45%;
      height: auto;
    }
    .emptyText {
      color: $n6Color;
      text-align: center;
    }
  }
  .attention-official-account {
    position: fixed;
    left: 0;
    z-index: 10;
    width: 100%;
    height: 128rpx;
    padding: 0 16rpx;
    .attentionContent {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      height: 100%;
      padding: 0 16rpx;
      background: rgba(0, 0, 0, 0.6);
      border-radius: 4px;
    }
    .icon-close {
      font-size: 48rpx;
      margin-right: 16rpx;
    }
    .left {
      display: flex;
      align-items: center; 
      font-size: 28rpx;
      line-height: 40rpx;
      color: #ffffff;
    }
    .go_attention {
      height: 64rpx;
      padding: 0 70rpx;
      font-size: 28rpx;
      border-radius: 64rpx;
      line-height: 64rpx;
      background-color: #E44435;
      color: #fff;
    }
  }
}
</style>
